﻿using SqlSugar;
using System.Reflection;

namespace Sunlight.Manage.MentApi.Utility.InitDatabaseExt
{
    /// <summary>
    /// 初始化数据库数据
    /// </summary>
    public static class InitDatabaseExt
    {

        /// <summary>
        /// 初始化数据库
        /// </summary>
        /// <param name="builder"></param>
        public static void InitDatabase(this WebApplicationBuilder builder) {

            //读取配置文件中的数据库连接信息
            string? connStr = builder.Configuration.GetConnectionString("connStr");

            if (string.IsNullOrWhiteSpace(connStr)) {
                throw new Exception("请配置数据库连接字符串");
            }

            ConnectionConfig connection = new ConnectionConfig() { 
                ConnectionString = connStr,
                DbType=DbType.SqlServer,
                IsAutoCloseConnection = true
            };

            using (SqlSugarClient client = new SqlSugarClient(connection)) {
                client.DbMaintenance.CreateDatabase();
                /*if (client.DbMaintenance.IsAnyTable("Sys_User", false)) {
                    client.DbMaintenance.DropTable("Sys_User");
                }*/

                Assembly assembly = Assembly.LoadFile(Path.Combine(AppContext.BaseDirectory, "Sunlight.Manage.Model.dll"));
                Type[] typeArray=assembly.GetTypes().Where(t=>t.Namespace.Equals("Sunlight.Manage.Model.Entity")).ToArray();

                client.CodeFirst.InitTables(typeArray);
            }
        }

    }
}
